﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using RilattackLibrary;
using System.ServiceModel;

namespace RilattackServer
{

    [ServiceBehavior(
        InstanceContextMode = InstanceContextMode.PerSession,
        ConcurrencyMode = ConcurrencyMode.Reentrant)]
    public class Server : IServer
    {
        public void StartServer()
        {
        }

        public bool login(string pseudo)
        {
            Console.WriteLine("Serveur receive new Login " + pseudo);
            App.PlayerCallBackMap = App.PlayerCallBackMap ?? new Dictionary<ICallBack,Player>();
            if (App.PlayerCallBackMap.Values.Any(x => x.Nickname == pseudo))
            {
                return false;
            }
            ICallBack client = OperationContext.Current.GetCallbackChannel<ICallBack>();
            if (!App.PlayerCallBackMap.ContainsKey(client))
            {
                Player pl = new Player(/*Nickname = pseudo*/);
                pl.Nickname = pseudo;
                App.PlayerCallBackMap.Add(client, pl);

                App.MainView.playersView.ItemsSource = App.PlayerCallBackMap.Values;
                App.MainView.playersView.Items.Refresh();
            }
            return true;
        }

        public void OnMessageReceived(ServerMessage message)
        {
            throw new System.NotImplementedException();
        }

        public Guid getMyUID()
        {
            Player p = null;
            App.PlayerCallBackMap.TryGetValue(OperationContext.Current.GetCallbackChannel<ICallBack>(), out p);
            return p.UID;
        }


        public void readyToPlay()
        {
            ICallBack client = OperationContext.Current.GetCallbackChannel<ICallBack>();
            Player currPlayer;
            App.PlayerCallBackMap.TryGetValue(client, out currPlayer);

            int x, y;
            foreach (Player p in App.PlayerCallBackMap.Values)
            {
                p.GetPosition(out x, out y);
                client.initialisePlayer(p.UID, p.Nickname, x, y);
            }
        }


        public void playerMove(int x, int y)
        {
            ICallBack client = OperationContext.Current.GetCallbackChannel<ICallBack>();
            Player currPlayer;
            App.PlayerCallBackMap.TryGetValue(client, out currPlayer);
            currPlayer.MoveBy(x, y);
        }
    }
}